package com.xqboss.apps.listener;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.xqboss.apps.constant.LockKey;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.box.Box;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.sys.SaleableEnum;
import com.xqboss.apps.service.box.BoxService;
import com.xqboss.apps.service.msg.PushService;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.core.redis.lock.LockValue;
import com.xqboss.common.core.redis.lock.RedisLock;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *     活动开始监听器
 * </p>
 * @author Trent
 * @date 2023/9/7
 */
@Component
public class BoxSaleStartListener extends MqListener {

    @Lazy
    @Autowired
    private PushService pushService;
    @Lazy
    @Autowired
    private BoxService boxService;

    @Override
    public MqEnum getEnum() {
        return AppMqDelayEnum.BOX_SALE_START;
    }

    @Override
    public ConsumeResult solve(MessageView message) {
        String value = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        long id = Long.parseLong(value);
        Box box = boxService.getById(id);
        if(Objects.nonNull(box)){
            if(Objects.equals(box.getSaleable(), SaleableEnum.SEQUENCE.getValue())){
                if(box.getPublishTimeStart() != null){
                    int between = (int) LocalDateTimeUtil.between(LocalDateTime.now(), box.getPublishTimeStart(), ChronoUnit.SECONDS);
                    if(Math.abs(between) < 60){
                        // 推送活动信息
                        pushService.pushBoxSaleMsg(box.getName(), box.getId());
                    }
                }
            }
        }
        return ConsumeResult.SUCCESS;
    }
}
